package com.qt.myboot.controller;


import com.qt.myboot.common.Result;
import com.qt.myboot.entity.User;
import com.qt.myboot.handler.BingdingResultHandler;
import com.qt.myboot.service.RedissonLockService;
import com.qt.myboot.service.UserService;
import com.qt.myboot.utils.IdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

@RestController
@RequestMapping("user")
@Api(description = "用户")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RedissonLockService lockService;

    @PostMapping(value = "/user_add")
    @RequiresPermissions({"user_add"})
    @ApiOperation(value = "添加用户")
    public Result<User> userAdd(@Valid @RequestBody User user, BindingResult bindingResult) {
        Result result = BingdingResultHandler.handler(bindingResult);
        if (!result.isSuccess()) {
            return result;
        }
        long l = idWorker.nextId();
        userService.addUser(user);
        return Result.success(l);
    }

    @GetMapping(value = "/user_query")
    @RequiresPermissions({"user_read"})
    @ApiOperation(value = "获取用户")
    public Result userQuery() {
        List<User> userList = userService.findAllUser();
        List<String> dates = new ArrayList<>();
        userList.forEach((vo) -> {
            dates.add(DateFormatUtils.format(vo.getCreateTime(), "yyyy-MM-dd HH:mm:ss", TimeZone.getTimeZone("Asia/Shanghai")));});

        Result result = Result.success();
        result.setData(userList);
        return result;

    }

    /**
     * @Description: 测试分布式锁接口 500个线程模拟秒杀
     * @Author: xusl
     * @Date: 2019/6/13 16:52
     * @Param: []
     * @return: void
     **/
    @GetMapping("/redisson")
    public void lock() {
        for (int i = 0; i < 500; i++) {
            new Thread(() ->{
                    lockService.update(new User(12, RandomUtils.nextInt(1,1000)+"", RandomUtils.nextInt(1,1000)+"",
                            RandomUtils.nextInt(1,1000)+"", RandomUtils.nextInt(1,1000)+"", new Date(), new Date()));
            }).start();
        }
    }
}
